package cn.lyh.controller;

import cn.lyh.entities.CommonResult;
import cn.lyh.entities.Payment;
//import lombok.extern.slf4j.Slf4j;
import cn.lyh.lb.LoadBalancer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.net.URI;
import java.util.List;

@RestController
@Slf4j
public class OrderController {

    @Resource
    private DiscoveryClient discoveryClient;
    @Resource
    private LoadBalancer loadBalancer;

    @Resource
    private RestTemplate restTemplate;


    //    public static final String PAYMENT_URL="http://localhost:8001";
    public static final String PAYMENT_URL = "http://CLOUD-PAYMENT-SERVICE";

    @GetMapping("/customer/get/{id}")
    public CommonResult<Payment> getPaymentById(@PathVariable("id") Long id) {
        return restTemplate.getForObject(PAYMENT_URL + "/payment/get/" + id, CommonResult.class);
    }

    @PostMapping("/customer/create")
    public CommonResult<Payment> create(@RequestBody Payment payment) {
        return restTemplate.postForObject(PAYMENT_URL + "/payment/create", payment, CommonResult.class);
    }

    @GetMapping("/customer/payment/sp")
    public String sp() {
        List<ServiceInstance> instances = discoveryClient.getInstances("cloud-payment-service");
        ServiceInstance instance = loadBalancer.instance(instances);
        if (instance == null || instances.size() <= 0) {
            return null;
        }
        URI uri = instance.getUri();
        return restTemplate.getForObject(uri + "/payment/sp", String.class);

    }


    @GetMapping(value = "/consumer/zipkin")
    public String getPaymentZipkin() {
        return "略略" + restTemplate.getForObject(PAYMENT_URL + "/payment/zipkin", String.class);
    }
}